import Vue from "vue";
import VueRouter from "vue-router";
import { getToken } from "@/utils/local-storage";
import { Toast } from "vant";
Vue.use(VueRouter);
const Home = () => import("../views/Home/home-index.vue");
const Layout = () => import("../views/Layout/layout-index.vue");
const Login = () => import("../views/Login/login-index.vue");
const Detail = () => import("../views/Detail/detail-index.vue")

const Register = () => import("../views/Register/register-index.vue");
const Test = () => import("../views/Test/test-index.vue");
const User = () => import("../views/User/user-index.vue");
const Article = () => import("../views/Article/article-index.vue");
const Collect = () => import("../views/Collect/collect-index.vue");
const Like = () => import("../views/Like/like-index.vue");
const routes = [
  {
    path: "/",
    redirect: "Layout",
  },
  {
    path: "/home",
    name: "home",
    component: Home,
  },
  {
    path: "/layout",
    name: "Layout",
    component: Layout,
    children: [
      {
        path: "user",
        name: "User",
        component: User,
      },
      {
        path: "collect",
        name: "Collect",
        component: Collect,
      },
      {
        path: "article",
        name: "Article",
        component: Article,
      },
      {
        path: "like",
        name: "Like",
        component: Like,
      },
    ],
  },
  {
    path: "/login",
    name: "Login",
    component: Login,
  },
  {
    path: "/detail/:id",
    name: "Detail",
    component: Detail,
  },
  {
    path: "/register",
    name: "Register",
    component: Register,
  },
  {
    path: "/test",
    name: "Test",
    component: Test,
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

// 设置白名单
const whiteList = ["/login", "/register", "/home", "/detail"];
router.beforeEach((to, from, next) => {
  if (getToken()) {
    next();
    return;
  }

  if (whiteList.indexOf(to.path) !== -1) {
    next();
    return;
  }

  Toast.fail("请先登录");
  next("/login");
});
export default router;
